<template>
    <view class="vue-tree">
        <NavTreeItem v-for="(item, index) in computedTreeData" :key="index" :tree-item-data="item" :active-id="activeId"
            @treeClickEvent="treeClickEvent" />
    </view>
</template>

<script>
import NavTreeItem from "@/components/productCategory/nav-tree-item.vue"
export default {
    name: "navTree",
    components: {
        NavTreeItem,
    },
    props: {
        // 树形控件数据
        treeData: {
            type: Array,
            default() {
                return []
            },
        },
        activeId: {
            type: Number,
            default: -1,
        },
    },
    data() {
        return {}
    },
    mounted() { },
    computed: {
        computedTreeData() {
            const _arr = this.treeData
            this.initData(_arr, 0)
            return _arr
        },
    },
    methods: {
        initData(arr, level) {
            if (arr && arr.length > 0) {
                arr.forEach((element) => {
                    if (element && !element.level) {
                        element.level = level
                    }
                    if (element.expand === undefined) {
                        element.expand = false
                    }
                    if (element.children && element.children.length > 0) {
                        this.initData(element.children, level + 1)
                    }
                })
            }
        },
        foldSameParentItem(arr, level, id, expand) {
            if (arr && arr.length > 0) {
                arr.forEach((element) => {
                    if (element && element.level === level) {
                        if (element.id === id) {
                            element.expand = !expand
                            if (Array.isArray(element.children) && element.children.length > 0) {
                                element.children.forEach((v) => {
                                    v.expand = false
                                })
                            }
                        } else {
                            element.expand = false
                        }
                    } else if (element.children && element.children.length > 0) {
                        this.foldSameParentItem(element.children, level, id, expand)
                    }
                })
            }
        },
        treeClickEvent(item) {
            this.foldSameParentItem(this.treeData, item.level, item.id, item.expand)
            this.$emit("treeClickEvent", item, this.treeData)
            this.$forceUpdate()
        },
    },
}
</script>
<style>
.vue-tree {
    display: flex;
    flex: 1;
    flex-direction: column;
    background: #f0f0f0;
    margin-right: 8rpx;
}
</style>
